package ar.com.unlp.fi.lrs.persist;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import ar.com.unlp.fi.lrs.domain.Actor;
import ar.com.unlp.fi.lrs.domain.Group;

@Repository
public class ActorDao extends AbstractDao {

	
	
	public void save(Actor actor) {

		try {

			session = HibernateUtil.getSessionFactory().openSession();

			tx = session.beginTransaction();

			session.save(actor);

			tx.commit();

		} catch (Exception e) {
			logger.error("Error al persistir", e);
		} finally {
			session.close();
		}

	}

	public Actor get(long id) {

		session = HibernateUtil.getSessionFactory().openSession();
		Actor actor = (Actor) session.get(Actor.class, id);
		tx = session.getTransaction();
		session.beginTransaction();
		tx.commit();
		
		session.close();
		return actor;

		
	}

	public void update(Actor actor) {
		try {

			session = HibernateUtil.getSessionFactory().openSession();

			tx = session.beginTransaction();

			session.update(actor);

			tx.commit();

		} catch (Exception e) {
			logger.error("Error al persistir", e);
		} finally {
			session.close();
		}

	}

	/**
	 * Retorna los grupos para un actor dado.
	 * 
	 * @param idAgent
	 * @return
	 */
	public List<Group> getGroups(long idAgent) {
		
		session = HibernateUtil.getSessionFactory().openSession();
		 
		
		Criteria crit = session.createCriteria(Group.class);
		crit.createAlias("members", "memebersAlias");
		crit.add(Restrictions.eq("memebersAlias.id", idAgent));
		
		List<Group> groups=crit.list();
		
		return groups;

		
	}

}
